﻿using Furion.FriendlyException;
using Gear.Core.ErrorControl;
using Gear.Core.Result;
using Gear.ToolKits.Helper;
using Gear.Web.Api.DynamicDataApi.Business;
using Gear.Web.Api.DynamicDataApi.Model;
using Gear.Web.Api.Entities.Entity;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Threading.Tasks;

namespace Gear.Web.Api.DynamicDataApi
{
    /// <summary>
    /// 动态接口
    /// </summary>
    public class DynamicDrivenController : Controller
    {
        public readonly IBusinessWorker _businessworker;
        public DynamicDrivenController(IBusinessWorker businessworker)
        {
            _businessworker = businessworker;
        }

        #region == 操作 ==

        #region == 操作接口 ==
        /// <summary>
        /// 接口驱动
        /// </summary>
        /// <returns></returns>
        public BaseResult DriveMethod()
        {
            BaseResult result = new ();

            try
            {
                // 路由检查
                var Ext = _ActionExt(new HttpRequestModel
                {
                    MethodType = HttpContext.Request.Method,
                    ControllerName = HttpContext.Items["Data_Driven_ControllerName"].ToString(),
                    ActionName = HttpContext.Items["Data_Driven_ActionName"].ToString(),
                    //VisionTag = HttpContext.Items["Data_Driven_VisionTag"].ToString(),
                    Authorization= HttpContext.Request.Headers.Authorization.ToString(),
                    QueryParam = HttpContext.Request.Method != "GET" ? null : QueryHash(HttpContext.Request.Query),
                    BodyParam = HttpContext.Request.Method != "POST" ?null : BodyHash(HttpContext.Request.ContentLength, HttpContext.Request.Body)
                });
                result.data= Ext;
                result.success= true;
            }
            catch(AppFriendlyException e)
            {
                result.message = e.Message;
                result.errorcode = e.ErrorCode.ToString();
            }
            
            
            return result;
        }

        /// <summary>
        /// 获取自定义字段
        /// </summary>
        /// <param name="actionId"></param>
        /// <returns></returns>
        public BaseResult GetField(int actionId)
        {
            BaseResult result = new ();

            try
            {
                // 路由检查
                result.data=_ActionDataForamt(actionId);
                result.success = true;
            }
            catch (AppFriendlyException e)
            {
                result.message = e.ErrorMessage.ToString();
                result.errorcode = e.ErrorCode.ToString();
            }

            return result;
        }
        #endregion

        #region == 操作驱动 ==
        /// <summary>
        /// 驱动执行
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        private object _ActionExt(HttpRequestModel model)=>_businessworker._ActionSorting(model);
        private bool _ActionDataForamt(int actionId) => _businessworker._ActionDataForamt(actionId);
        #endregion

        #endregion

        #region == 配置 ==

        #region == 配置接口 ==
        public async Task<BaseResult> SystemPages()
        {
            BaseResult result = new();

            try
            {
                // 路由检查
                result.data = new { result = await _businessworker.SystemPages() };
                result.success = true;
            }
            catch (AppFriendlyException e)
            {
                result.message = e.ErrorMessage.ToString();
                result.errorcode = e.ErrorCode.ToString();
            }

            return result;
        }
        public async Task<BaseResult> AreaPages(int systemid)
        {
            BaseResult result = new();

            try
            {
                // 路由检查
                result.data = new { result = await _businessworker.AreaPages(systemid) };
                result.success = true;
            }
            catch (AppFriendlyException e)
            {
                result.message = e.ErrorMessage.ToString();
                result.errorcode = e.ErrorCode.ToString();
            }

            return result;

        }
        public async Task<BaseResult> ConnectionPoolPages(int systemid)
        {
            BaseResult result = new();

            try
            {
                // 路由检查
                result.data = new { result = await _businessworker.ConnectionPoolPages(systemid)};
                result.success = true;
            }
            catch (AppFriendlyException e)
            {
                result.message = e.ErrorMessage.ToString();
                result.errorcode = e.ErrorCode.ToString();
            }

            return result;
        }
        public async Task<BaseResult> ControllerPages(int areaid)
        {
            BaseResult result = new();

            try
            {
                // 路由检查
                result.data = new { result = await _businessworker.ControllerPages(areaid) };
                result.success = true;
            }
            catch (AppFriendlyException e)
            {
                result.message = e.ErrorMessage.ToString();
                result.errorcode = e.ErrorCode.ToString();
            }

            return result;
        }
        public async Task<BaseResult> ActionPages(int controllerid)
        {
            BaseResult result = new();

            try
            {
                // 路由检查
                result.data = new { result = await _businessworker.ActionPages(controllerid) };
                result.success = true;
            }
            catch (AppFriendlyException e)
            {
                result.message = e.ErrorMessage.ToString();
                result.errorcode = e.ErrorCode.ToString();
            }

            return result;
        }
        public async Task<BaseResult> FieldPages(int actionid)
        {
            BaseResult result = new();

            try
            {
                // 路由检查
                result.data = new { result = await _businessworker.FieldPages(actionid) };
                result.success = true;
            }
            catch (AppFriendlyException e)
            {
                result.message = e.ErrorMessage.ToString();
                result.errorcode = e.ErrorCode.ToString();
            }

            return result;
        }
        
        [HttpPost]
        public async Task<BaseResult> SystemEdit([FromForm]Sys_cluster dto)
        {

            BaseResult result = new();

            try
            {
                // 路由检查
                result.data = new { result = await _businessworker.SystemEdit(dto) };
                result.success = true;
            }
            catch (AppFriendlyException e)
            {
                result.message = e.ErrorMessage.ToString();
                result.errorcode = e.ErrorCode.ToString();
            }

            return result;
        }
        [HttpPost]
        public async Task<BaseResult> AreaEdit([FromForm] Api_area dto)
        {

            BaseResult result = new();

            try
            {
                // 路由检查
                result.data = new { result = await _businessworker.AreaEdit(dto) };
                result.success = true;
            }
            catch (AppFriendlyException e)
            {
                result.message = e.ErrorMessage.ToString();
                result.errorcode = e.ErrorCode.ToString();
            }

            return result;
        }
        [HttpPost]
        public async Task<BaseResult> ConnectionPoolEdit([FromForm] Sys_connectionpool dto)
        {

            BaseResult result = new();

            try
            {
                // 路由检查
                result.data = new { result = await _businessworker.ConnectionPoolEdit(dto) };
                result.success = true;
            }
            catch (AppFriendlyException e)
            {
                result.message = e.ErrorMessage.ToString();
                result.errorcode = e.ErrorCode.ToString();
            }

            return result;
        }
        [HttpPost]
        public async Task<BaseResult> ControllerEdit([FromForm] Api_controller dto)
        {

            BaseResult result = new();

            try
            {
                // 路由检查
                result.data = new { result = await _businessworker.ControllerEdit(dto) };
                result.success = true;
            }
            catch (AppFriendlyException e)
            {
                result.message = e.ErrorMessage.ToString();
                result.errorcode = e.ErrorCode.ToString();
            }

            return result;
        }
        [HttpPost]
        public async Task<BaseResult> ActionEdit([FromForm] Api_action dto)
        {

            BaseResult result = new();

            try
            {
                // 路由检查
                result.data = new { result = await _businessworker.ActionEdit(dto) };
                result.success = true;
            }
            catch (AppFriendlyException e)
            {
                result.message = e.ErrorMessage.ToString();
                result.errorcode = e.ErrorCode.ToString();
            }

            return result;
        }
        [HttpPost]
        public async Task<BaseResult> FieldEdit([FromForm] Api_field dto)
        {

            BaseResult result = new();

            try
            {
                // 路由检查
                result.data = new { result = await _businessworker.FieldEdit(dto) };
                result.success = true;
            }
            catch (AppFriendlyException e)
            {
                result.message = e.ErrorMessage.ToString();
                result.errorcode = e.ErrorCode.ToString();
            }

            return result;
        }

        #endregion

        #endregion

        #region == Tool ==
        // 获取Query参数
        private static Dictionary<string, object> QueryHash(IQueryCollection query)
        {
            try
            {
                var keys = query.Keys;
                Dictionary<string, object> parameters = new();

                foreach (var key in keys)
                {
                    parameters.Add(key, query[key].ToString());
                }
                CheckKeyOnly(parameters);
                return parameters;

            }
            catch (Exception)
            {
                throw Oops.Oh(ErrorCodeModel.E1100_2,"");
            }
            
        }
        // 获取Body参数
        private static Dictionary<string, object> BodyHash(long? length,Stream body)
        {
            try
            {
                string postJson = string.Empty;
                if (length != null && length > 0)
                {
                    // 使用这个方式读取，并且使用异步
                    StreamReader streamReader = new(body, Encoding.UTF8);
                    postJson = streamReader.ReadToEndAsync().Result;
                }
                // 解析json对象
                var res= JsonHelper.DeserializeJSON<Dictionary<string, object>>(postJson);
                CheckKeyOnly(res);
                return res;
            }
            
            catch (Exception)
            {
                throw Oops.Oh(ErrorCodeModel.E1100_3,"");
            }

        }
        // 判断参数唯一
        private static void CheckKeyOnly(Dictionary<string, object> param)
        {
            List<string> list= new ();
            if (param == null) return;
            foreach(KeyValuePair<string, object> kvp in param)
            {
                if (list.Contains(kvp.Key))
                {
                    throw Oops.Oh(ErrorCodeModel.E1200_2, kvp.Key);
                }
                else
                {
                    list.Add(kvp.Key);
                }

            }
        }
        #endregion
    }
}
